package cn.ll.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import cn.ll.po.Contract;
import cn.ll.po.Department;
import cn.ll.po.Item;
import cn.ll.po.Task;
import cn.ll.po.User;
import cn.ll.service.ContractService;
import cn.ll.service.DepartmentService;
import cn.ll.service.ItemService;
import cn.ll.service.TaskService;
import cn.ll.vo.LoginUser;

public class TaskAction extends Action {

	public void save(HttpServletRequest request, HttpServletResponse response) {
		String contractid = request.getParameter("contractid");
		// String type = request.getParameter("type");
		// String status = request.getParameter("status");
		String pmgrid = request.getParameter("pmgrid");
		String pmgrname = request.getParameter("pmgrid");
		String pastid = request.getParameter("pastid");
		String pastname = request.getParameter("pastname");
		String departmentid = request.getParameter("departmentid");
		String itemlist_str = request.getParameter("itemlist");

		LoginUser cur_user = (LoginUser) request.getSession().getAttribute("CURRENT_USER");
		ContractService contractService = (ContractService) this.getApplicationContext().getBean("contractService");
		TaskService taskService = (TaskService) this.getApplicationContext().getBean("taskService");
		DepartmentService departmentService = (DepartmentService) this.getApplicationContext().getBean(
				"departmentService");
		Department department = departmentService.findById(Integer.parseInt(departmentid));
		Contract contract = contractService.findById(contractid);

		Task task = new Task();
		task.setContractid(contractid);
		task.setRootid(contract.getRootid());
		task.setCreateuser(cur_user.getUser().getId());
		task.setCreateusername(cur_user.getUser().getUsername());
		task.setType(0);
		task.setStatus(0);
		task.setPmgrid(pmgrid);
		task.setPmgrname(pmgrname);
		task.setPastid(pastid);
		task.setPastname(pastname);
		task.setDepartmentid(Integer.parseInt(departmentid));

		task.setDepname(department.getDepartmentName());
		task.setCreatetime(new Date());

		// 保存订单
		taskService.save(task);

		// 添加子项目(其实是设置子项中的订单号)
		JSONArray jsa = JSONArray.fromObject(itemlist_str);
		ItemService itemService = (ItemService) this.getApplicationContext().getBean("itemService");

		int len = jsa.size();
		for (int i = 0; i < len; i++) {
			JSONObject jso = jsa.getJSONObject(i);
			int iid = jso.getInt("id");
			Item item = itemService.findById(iid);
			if (item != null) {
				item.setTaskid(task.getId());// 设置订单ID
				itemService.update(item);
			}
		}

		Map rs = new HashMap();
		rs.put("success", true);
		rtn(rs, request, response);
	}

	/**
	 * 删除订单.task订单类型为0时,才允许操作. 删除规则:先解除订单下的子项与该订单的关系,即删除子项中的订单号;然后从数据库表中删除改订单
	 * 
	 * @param request
	 * @param response
	 */
	public void delete(HttpServletRequest request, HttpServletResponse response) {

		String task_id_list = request.getParameter("itemlist");
		JSONArray jsa = JSONArray.fromObject(task_id_list);
		if (jsa != null) {
			int len = jsa.size();
			for (int i = 0; i < len; i++) {
				JSONObject jso = jsa.getJSONObject(i);
				String taskid = jso.getString("id");
				TaskService taskService = (TaskService) this.getApplicationContext().getBean("taskService");
				ItemService itemService = (ItemService) this.getApplicationContext().getBean("itemService");

				Task task = taskService.findById(taskid);
				if (task != null && task.getType() == 0) {// 为订单类型时才可以删除
					List<Item> itemlist = itemService.findByTaskid(task.getId());
					if (itemlist != null) {
						int item_len = itemlist.size();
						for (int j = 0; j < item_len; j++) {
							Item item = itemlist.get(j);
							item.setTaskid(null);// 设置该订单下的子项目,即把子项的订单ID置空
							itemService.update(item);
						}
					}
					taskService.delete(task);// 删除定单

				}

			}
			Map rs = new HashMap();
			rs.put("success", true);
			rtn(rs, request, response);
			return;
		}
		Map rs = new HashMap();
		rs.put("success", false);
		rtn(rs, request, response);
		return;
	}

	/**
	 * 根据task的id,查询该task的信息
	 * 
	 * @param request
	 * @param response
	 */
	public void findById(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		if (id != null && id.length() > 0) {
			TaskService taskService = (TaskService) this.getApplicationContext().getBean("taskService");
			Task task = taskService.findById(id);
			if (task != null) {
				List list = new ArrayList();
				list.add(task);

				Map rs = new HashMap();
				rs.put("items", list);
				rs.put("success", true);
				rtn(rs, request, response);
				return;
			}

		}

		Map rs = new HashMap();
		rs.put("success", false);
		rtn(rs, request, response);
		return;
	}

	/**
	 * 订单(type 为0)的列表 type 0:订单;1:工作单;2:交付单
	 * 
	 * @param request
	 * @param response
	 */
	public void taskorder(HttpServletRequest request, HttpServletResponse response) {
		TaskService taskService = (TaskService) this.getApplicationContext().getBean("taskService");
		String status = request.getParameter("status");// -1:所有;0:待审批;1:审批通过;2:审批不通过
		int type = 0;// 订单
		List<Task> list = taskService.selectTaskByTypeAndStatus(type, Integer.parseInt(status));
		Map rs = new HashMap();
		rs.put("items", list);
		rtn(rs, request, response);
		return;
	}

	/**
	 * 工作单(type 为1)的列表 type 0:订单;1:工作单;2:交付单
	 * 
	 * @param request
	 * @param response
	 */
	public void taskwork(HttpServletRequest request, HttpServletResponse response) {
		TaskService taskService = (TaskService) this.getApplicationContext().getBean("taskService");
		String status = request.getParameter("status");// -1:所有;0:待审批;1:审批通过;2:审批不通过
		int type = 1;// 工作单
		List<Task> list = taskService.selectTaskByTypeAndStatus(type, Integer.parseInt(status));
		Map rs = new HashMap();
		rs.put("items", list);
		rtn(rs, request, response);
		return;
	}

	/**
	 * 完成单(type 为2)的列表 type 0:订单;1:工作单;2:交付单
	 * 
	 * @param request
	 * @param response
	 */
	public void taskfinish(HttpServletRequest request, HttpServletResponse response) {
		TaskService taskService = (TaskService) this.getApplicationContext().getBean("taskService");
		String status = request.getParameter("status");// -1:所有;0:待审批;1:审批通过;2:审批不通过
		int type = 2;// 交付单
		List<Task> list = taskService.selectTaskByTypeAndStatus(type, Integer.parseInt(status));
		Map rs = new HashMap();
		rs.put("items", list);
		rtn(rs, request, response);
		return;
	}

	/**
	 * 更新订单状态 type 0:订单;1:工作单;2:交付单
	 * 
	 * @param request
	 * @param response
	 */
	public void updateOrderStatus(HttpServletRequest request, HttpServletResponse response) {

		String task_status_str = request.getParameter("itemlist");
		TaskService taskService = (TaskService) this.getApplicationContext().getBean("taskService");

		LoginUser loginUser = (LoginUser) request.getSession().getAttribute("CURRENT_USER");

		JSONArray jsa = JSONArray.fromObject(task_status_str);
		int len = jsa.size();
		for (int i = 0; i < len; i++) {
			JSONObject jso = jsa.getJSONObject(i);
			String taskid = jso.getString("id");
			int status = jso.getInt("status");
			Task task = taskService.findById(taskid);
			if (task.getType() == 0) {
				if (status == 1) {// 如果是审批通过，则该订单就变成了工作单
					task.setType(1);
					task.setStatus(0);
					task.setVerifytime(new Date(System.currentTimeMillis()));
					task.setVerifyuser(loginUser.getUser().getUsername());
				} else {
					task.setStatus(status);
					task.setVerifytime(new Date(System.currentTimeMillis()));
					task.setVerifyuser(loginUser.getUser().getUsername());
				}

				taskService.update(task);
			}
		}
		Map rs = new HashMap();
		rs.put("success", true);
		rtn(rs, request, response);
		return;
	}

	/**
	 * 更新工作单状态 type 0:订单;1:工作单;2:交付单
	 * 
	 * @param request
	 * @param response
	 */
	public void updateWorkStatus(HttpServletRequest request, HttpServletResponse response) {
		String task_status_str = request.getParameter("itemlist");
		TaskService taskService = (TaskService) this.getApplicationContext().getBean("taskService");
		JSONArray jsa = JSONArray.fromObject(task_status_str);

		LoginUser loginUser = (LoginUser) request.getSession().getAttribute("CURRENT_USER");

		int len = jsa.size();
		for (int i = 0; i < len; i++) {
			JSONObject jso = jsa.getJSONObject(i);
			String taskid = jso.getString("id");
			int status = jso.getInt("status");
			Task task = taskService.findById(taskid);
			if (task.getType() == 1) {
				if (status == 2) {// 如果是工作完成，则该工作单就变成交付单了
					task.setType(2);
					task.setStatus(0);
					task.setWorkfinishtime(new Date(System.currentTimeMillis()));
				} else {
					task.setStatus(status);
					task.setWorkstarttime(new Date());
				}

				taskService.update(task);
			}
		}
		Map rs = new HashMap();
		rs.put("success", true);
		rtn(rs, request, response);
		return;
	}

	/**
	 * 更新交付单 type 0:订单;1:工作单;2:交付单
	 * 
	 * @param request
	 * @param response
	 */
	public void updateFinishStatus(HttpServletRequest request, HttpServletResponse response) {
		String task_status_str = request.getParameter("itemlist");
		TaskService taskService = (TaskService) this.getApplicationContext().getBean("taskService");

		LoginUser loginUser = (LoginUser) request.getSession().getAttribute("CURRENT_USER");

		JSONArray jsa = JSONArray.fromObject(task_status_str);
		int len = jsa.size();
		for (int i = 0; i < len; i++) {
			JSONObject jso = jsa.getJSONObject(i);
			String taskid = jso.getString("id");
			int status = jso.getInt("status");
			Task task = taskService.findById(taskid);
			if (task.getType() == 2) {
				if (status == 2) {// 如果是审批不通过，则该交付单就变成工作单
					task.setType(1);// 置成工作单
					task.setStatus(2);// 审核不通过
					task.setPastid(loginUser.getUser().getId());
					task.setPastname(loginUser.getUser().getUsername());
					task.setPasttime(new Date());
				} else {
					task.setStatus(status);
					task.setPastid(loginUser.getUser().getId());
					task.setPastname(loginUser.getUser().getUsername());
					task.setPasttime(new Date());
				}

				taskService.update(task);
			}
		}
		Map rs = new HashMap();
		rs.put("success", true);
		rtn(rs, request, response);
		return;
	}

	/**
	 * 给工作单分配工作 type 0:订单;1:工作单;2:交付单
	 * 
	 * @param request
	 * @param response
	 */
	public void assignWork(HttpServletRequest request, HttpServletResponse response) {
		String taskid = request.getParameter("id");
		String taskdetail = request.getParameter("taskdetail");

		TaskService taskService = (TaskService) this.getApplicationContext().getBean("taskService");
		Task task = taskService.findById(taskid);
		int work_type = 1;
		int not_assign = 0;
		if (task != null && task.getType() == work_type && task.getStatus() == not_assign) {
			task.setTaskdetail(taskdetail);
			task.setStatus(1);
			task.setWorkstarttime(new Date());
			taskService.update(task);

			Map rs = new HashMap();
			rs.put("success", true);
			rtn(rs, request, response);
			return;
		} else {
			Map rs = new HashMap();
			rs.put("success", false);
			rtn(rs, request, response);
			return;
		}
	}

	/**
	 * 根据协议ID获取
	 * 
	 * @param request
	 * @param response
	 */
	public void itemsall(HttpServletRequest request, HttpServletResponse response) {
		ItemService itemService = (ItemService) this.getApplicationContext().getBean("itemService");
		String taskid = request.getParameter("id");
		List<Item> list = itemService.findByTaskid(taskid);
		Map rs = new HashMap();
		rs.put("items", list);
		rtn(rs, request, response);
		return;

	}
}
